package com.rzgeo.rzmaplib.comp;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.FeatureTable;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.rzgeo.rzmaplib.R;
import com.rzgeo.rzmaplib.util.RmlUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class RmlPhotosViewer extends FrameLayout {
    private ImageSwitcher imsw_imgs;
//    private EditText tin_name;
//    private EditText tin_time;
//    private EditText tin_lat;
//    private EditText sp_lng;
//    private EditText tin_alt;
//    private EditText tin_loc_tol;
//    private EditText tin_yaw;
    private Button btn_delete;
    private Button btn_cancel;
    private FeatureLayer _featureLayer;
    
    private Map<String,EditText>_key2Input=new HashMap<>();
    private int _selectPhoto=-1;
    private ArrayList<Feature> _photoFeatures;
    private View btn_pre;
    private View btn_next;
    private OnResult _onResult;

    public interface OnResult{
        /***
         * 删除
         */
        void onDelete(Feature feature);

        /***
         * 取消
         */
        void onCancel();
    }

    public RmlPhotosViewer(@NonNull Context context) {
        super(context);
        initUI(context);
    }

    public RmlPhotosViewer(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initUI(context);
    }

    public RmlPhotosViewer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initUI(context);
    }

    private void initUI(Context context) {
        View subView = LayoutInflater.from(context).inflate(R.layout.comp_photo_viewer, null);
        subView.setLayoutParams(
                new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        this.addView(subView);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        imsw_imgs=findViewById(R.id.imsw_imgs);
//        =findViewById(R.id.);
//        tin_name=findViewById(R.id.tin_name);
//        tin_time=findViewById(R.id.tin_time);
//        sp_lng=findViewById(R.id.sp_lng);
//        tin_lat=findViewById(R.id.tin_lat);
//        tin_alt=findViewById(R.id.tin_alt);
//        tin_loc_tol=findViewById(R.id.tin_loc_tol);
//        tin_yaw=findViewById(R.id.tin_yaw);
        _key2Input.put("NAME", (EditText) findViewById(R.id.tin_name));
        _key2Input.put("TIME",(EditText) findViewById(R.id.tin_time));
        _key2Input.put("LNG",(EditText) findViewById(R.id.sp_lng));
        _key2Input.put("LAT",(EditText) findViewById(R.id.tin_lat));
        _key2Input.put("ALT",(EditText) findViewById(R.id.tin_alt));
        _key2Input.put("TOL",(EditText) findViewById(R.id.tin_loc_tol));
        _key2Input.put("YAW",(EditText) findViewById(R.id.tin_yaw));
        _key2Input.put("REMARK",(EditText) findViewById(R.id.tin_yaw));

        btn_delete=findViewById(R.id.btn_delete);
        btn_cancel=findViewById(R.id.btn_cancel);
        btn_pre=findViewById(R.id.btn_pre);
        btn_next=findViewById(R.id.btn_next);

        imsw_imgs.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView imageView = new ImageView(getContext());
                return imageView;
            }
        });
        imsw_imgs.setInAnimation(getContext(), android.R.anim.fade_in);
        imsw_imgs.setOutAnimation(getContext(), android.R.anim.fade_out);

        btn_delete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                final Feature f = _photoFeatures.get(_selectPhoto);
                FeatureTable ft = _featureLayer.getFeatureTable();
                if(!ft.canDelete(f))
                {
                    RmlUtil.Tip.Toast("该要素无法删除");
                }else{
                    final ListenableFuture<Void> df = ft.deleteFeatureAsync(f);
                    df.addDoneListener(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                df.get();
                                _onResult.onDelete(f);
                            } catch (Exception e) {
                                RmlUtil.Tip.Toast("删除要素失败");
                            }
                        }
                    });
                }

            }
        });
        btn_cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                _onResult.onCancel();
            }
        });

        OnClickListener switchImgClick = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(_photoFeatures==null||_photoFeatures.size()==0)
                    return;

                if(v.getId()==R.id.btn_pre)
                    _selectPhoto--;
                else
                    _selectPhoto++;

                if(_selectPhoto<0)
                    setSelection(_photoFeatures.size()-1);
                else if(_selectPhoto>=_photoFeatures.size())
                    setSelection(0);
            }
        };
        btn_pre.setOnClickListener(switchImgClick);
        btn_next.setOnClickListener(switchImgClick);

    }

    public void setup(FeatureLayer featureLayer, QueryParameters qp, @NonNull OnResult onResult){
        _onResult=onResult;
        clearDatas();

        _featureLayer=featureLayer;
        if(!_featureLayer.isVisible()){
            _featureLayer.setVisible(true);
        }

        final ListenableFuture<FeatureQueryResult> qf = _featureLayer.selectFeaturesAsync(qp, FeatureLayer.SelectionMode.NEW);
        qf.addDoneListener(new Runnable() {
            @Override
            public void run() {
                ArrayList<Feature> photoFeatures = RmlUtil.Features.getQueryResult(qf);
                if(photoFeatures!=null){
                    _photoFeatures=photoFeatures;
                    setSelection(0);
                }
            }
        });
    }

    private void setSelection(int i) {
        _selectPhoto=i;
        if(_photoFeatures!=null&&_photoFeatures.size()>0
                &&i>0&&i<_photoFeatures.size()){
            Feature pf = _photoFeatures.get(i);

            Map<String, Object> attr = pf.getAttributes();
            for(String key:_key2Input.keySet()){
                _key2Input.get(key).setText(RmlUtil.Dict.getString(attr,key));
            }

            String path = RmlUtil.Dict.getString(attr, "PATH");
            Drawable bd = BitmapDrawable.createFromPath(path);
            imsw_imgs.setImageDrawable(bd);
        }
    }

    private void clearDatas() {

        imsw_imgs.setImageDrawable(
                getContext().getResources().getDrawable(R.drawable.ic_no_pic)
        );

        for(String key:_key2Input.keySet()){
            _key2Input.get(key).setText("");
        }

        _selectPhoto=-1;
    }

    public interface OnTakePhotoResult {
        void onResult(File file);
        void onCancel();
    }
}
